<script setup>
import { ref, inject, watch, onBeforeUnmount } from 'vue'
import { PointLayer } from '@antv/l7'
import axios from 'axios'
import { useCityLayers } from '@/composable/useCityLayers.js'

// 图层管理函数
const { updateLayerList } = useCityLayers()

const { map, scene } = inject('mapScene')
watch(
  [map, scene],
  async ([newMap, newScene]) => {
    if (newMap && newScene) {
      newMap.flyTo({
        center: [114.3055, 30.5928], // 武汉市中心坐标 [经度, 纬度]
        zoom: 11,
        pitch: 60,
        bearing: -20,
      })
      // 添加点图层
      await addPointLayer(newScene)
    }
  },
  { immediate: true },
)

// 添加点图层的函数  http://localhost:3001/Wuhan_events
async function addPointLayer(scene) {
  if (!scene) return
  const res = await axios.get('http://localhost:3001/Wuhan_events')
  const pointLayer = new PointLayer({
    zIndex: 1,
    name: 'eventPoint',
  })
  pointLayer
    .source(res.data)
    .size(10)
    .shape('circle')
    .active(true)
    .animate(true)
    .size(40)
    .color('#ffa842')
    .style({
      offsets: [40, 40],
    })
  scene.addLayer(pointLayer)
  pointLayer.hide() // 默认隐藏点图层
  // 添加完图层后，更新图层管理模块的图层状态数据
  updateLayerList(scene)
}

onBeforeUnmount(() => {
  // 组件卸载前移除图层
  const layer = scene.value.getLayerByName('eventPoint')
  scene.value.removeLayer(layer)
  updateLayerList(scene.value)
})
</script>

<template>
  <div></div>
</template>

<style scoped></style>
